import request from "../request.js"
import cfg from "../config.js"

let page_type = {
    open: function (page_info) {
        let page_html_id=page_info.page_html_id;
        let property=page_info.property;
        let ext_js=page_info.ext_js;
        let page_id=page_info.page_id;
        let rights=page_info.rights;
        let params=page_info.params;
        $("#" + page_html_id).addClass("form-visible-builder-page row");
        $("#" + page_html_id).html("\
        <style>.config-part-each{display:flex;flex-wrap:wrap;}</style> \
        <div class='col-md-6 col-sm-12 col-xs-12' style='padding:0.8rem;'>\
            <div class='view-part'></div>\
        </div>\
        <div class='col-md-6 col-sm-12 col-xs-12' style='padding:0.8rem;'>\
            <div class='config-part'></div>\
        </div>");

        let amisJSON = {
            //////////////////配置面板//////////////////
            "type": "page",
            "name": page_html_id + "_config",
            "body": [
                {
                    "type": "tabs",
                    "mode": "normal",
                    "className": "config-tabs",
                    "toolbar": [],
                    "tabs": [
                        {
                            "title": "表单配置",
                            "tab": {
                                "type": "form",
                                "name": "config_form",
                                "api": cfg.api_server + "formbuilder/quickbuild",
                                "title": "",
                                "resetAfterSubmit": true,
                                "redirect": "index.html", //?pid=${form_page_id}
                                "persistData": "form-visible-builder-page",
                                "clearPersistDataAfterSubmit": true,
                                "multiple": true,
                                "actions": [
                                  {
                                    "type": "reset",
                                    "label": "重置"
                                  },
                                  {
                                    "type": "submit",
                                    "level": "primary",
                                    "label": "一键生成表单"
                                  }
                                ],
                                "controls": [
                                    {
                                        "type": "service",
                                        "name": "configer",
                                        "data": {
                                            "api_server": cfg.api_server
                                        },
                                        "schemaApi": {
                                            "method": "post",
                                            "url": cfg.api_server + "configer/getbyname",
                                            "requestAdaptor": function (api) {
                                                api.data.name = "form_quick_builder";
                                            },
                                            "adaptor": function (payload, response) {
                                                return payload;
                                            }
                                        }
                                    }
                                ]
                            }
                        },
                        {
                            "title": "控件",
                            "tab": {
                                "type": "form",
                                "title": "",
                                "submitText": "",
                                "data": {
                                    "each": [
                                        {
                                            "type": "text",
                                            "label": "文本",
                                            "icon": "fa-pencil"
                                        },
                                        {
                                            "type": "textarea",
                                            "label": "文本域",
                                            "icon": "fa-edit"
                                        },
                                        {
                                            "type": "number",
                                            "label": "数字",
                                            "icon": "fa-calculator"
                                        },
                                        {
                                            "type": "date",
                                            "label": "日期",
                                            "icon": "fa-calendar"
                                        },
                                        {
                                            "type": "datetime",
                                            "label": "时间",
                                            "icon": "fa-clock-o"
                                        },
                                        {
                                            "type": "switch",
                                            "label": "开关",
                                            "icon": "fa-toggle-on"
                                        },
                                        {
                                            "type": "file",
                                            "label": "文件",
                                            "icon": "fa-folder-o"
                                        },
                                        {
                                            "type": "image",
                                            "label": "图片",
                                            "icon": "fa-image"
                                        },
                                        {
                                            "type": "select",
                                            "label": "下拉选项框",
                                            "icon": "fa-caret-square-o-down"
                                        },
                                        {
                                            "type": "radios",
                                            "label": "单选列表",
                                            "icon": "fa-check-circle-o"
                                        },
                                        {
                                            "type": "checkboxes",
                                            "label": "多选列表",
                                            "icon": "fa-check-square-o"
                                        },
                                        {
                                            "type": "related",
                                            "label": "关联字段",
                                            "icon": "fa-external-link"
                                        },
                                        {
                                            "type": "fieldSet",
                                            "label": "[字段分组]",
                                            "icon": "fa-list-alt"
                                        }
                                    ]
                                },
                                "body": [
                                    {
                                        "type": "each",
                                        "label": "静态展示each",
                                        "className": "config-part-each",
                                        "name": "each",
                                        "items": {
                                            "type": "tpl",
                                            "tpl": "<div class='new-item' data-type='<%= data.type %>' style='padding:0.5rem 1rem;margin:0.5rem;cursor:move;width:120px;height:38px;border:solid 1px #aaa;' draggable='true'>\
                                        <i class='fa <%= data.icon %>'></i> <%= data.label %></div>"
                                        }
                                    }
                                ]
                            }
                        }
                    ]
                }
            ]
        }
        let amis = amisRequire('amis/embed');
        let config_amisScoped = amis.embed(
            '#' + page_html_id + " .config-part", amisJSON, {},
            {
                theme: 'antd'
            }
        );

        $('#' + page_html_id + " .config-part .config-tabs>ul>li").eq(0).click(function () {
            $('#' + page_html_id + " .view-part").parent().removeClass("col-md-8");
            $('#' + page_html_id + " .config-part").parent().removeClass("col-md-4");
            $('#' + page_html_id + " .view-part").parent().addClass("col-md-6");
            $('#' + page_html_id + " .config-part").parent().addClass("col-md-6");
        })
        $('#' + page_html_id + " .config-part .config-tabs>ul>li").eq(1).click(function () {
            $('#' + page_html_id + " .view-part").parent().removeClass("col-md-6");
            $('#' + page_html_id + " .config-part").parent().removeClass("col-md-6");
            $('#' + page_html_id + " .view-part").parent().addClass("col-md-8");
            $('#' + page_html_id + " .config-part").parent().addClass("col-md-4");
        })

        let refresh = function () {
            if ($('#' + page_html_id + " .view-part").length == 0) return;
            let data = config_amisScoped.getComponentByName(page_html_id + "_config.config_form").getValues();
            let controls = data.datamodel_source_type == "新建" ? data.controls_new : data.controls_old;
            let add_form_controls = build_form_controls(controls);
            let viewJSON =
            {
                "type": "page",
                "body": [
                    {
                        "type": "html",
                        "html": (data.title ? "<center><h1>" + data.title + "</h1></center>" : "") + (data.subtitle ? "<center><h4>" + data.subtitle + "</h4></center>" : "")
                    },
                    {
                        "type": "form",
                        "title": "",
                        "submitText": "",
                        "mode": "normal",
                        "controls": add_form_controls
                    },
                    {
                        "type": "html",
                        "html": data.description ? "<span>" + data.description + "</span>" : ""
                    }
                ]
            }
            let view_amisScoped = amis.embed(
                '#' + page_html_id + " .view-part", viewJSON, {},
                {
                    theme: 'antd'
                }
            );
            //界面操作
            let scope = '#' + page_html_id + " .view-part";
            let items = $(scope).find(".antd-Form-item,fieldset");
            let groups = $(scope).find(".antd-Form-group");
            items.css("position", "relative");
            items.each(function (index, element) {
                $(this).data("id", index);
                $(this).attr("title", "鼠标按住拖动");
                if ($(this).find(".item-close").length == 0) {
                    $(this).find(">label:first,>legend:first").append('<span class="fa fa-trash item-close" style="visibility:hidden;position:absolute;top:0.3rem;right:0.3rem;cursor:pointer;" data-id=' + index + ' title="删除"></span>')
                }
            })
            items.hover(function () {
                $(this).css("border", "dashed 1px #3c8dbc");
                $(this).find(".item-close:first").css("visibility", "visible");
            }, function () {
                $(this).css("border", "solid 1px #fff");
                $(this).find(".item-close").css("visibility", "hidden");
            });
            items.attr("draggable", true);
            items.css("cursor", "move");
            items.find(".antd-Form-label").css("cursor", "move");
            items.each((index, element) => {
                let item = $(element);
                let is_fieldSet=(element.type=="fieldset");
                if (!is_fieldSet) {
                    element.ondragstart = function (ev) {
                        item.css("background", "#ddd");
                        ev.dataTransfer.setData("Text", $(ev.target).data("id")); //将类似ID的属性传递                        
                        ev.stopPropagation();
                    }
                    element.ondragover = function (ev) {
                        //根据鼠标位置判断放到组内还是组外
                        if (ev.clientX - item.offset().left > 0.7 * item.width()) {
                            item.css("border-right", "solid 5px #1890ff");
                            item.parent().parent().css("border-bottom", "");
                        }
                        else {
                            item.parent().parent().css("border-bottom", "solid 3px #1890ff");
                            item.css("border-right", "");
                        }
                        ev.preventDefault();
                        ev.stopPropagation();
                    }
                    element.ondragleave = function (ev) {
                        item.css("border-right", "");
                        item.parent().parent().css("border-bottom", "");
                        items.css("background", "");
                    }
                    element.ondrop = function (ev) {
                        items.css("border-right", "");
                        items.parent().parent().css("border-bottom", "");
                        items.css("background", "");
                        //自动组号
                        auto_group_no(controls);
                        var source = ev.dataTransfer.getData("Text");
                        item.parent().parent().css("border-bottom", "");
                        let target = index;
                        //这里获取到类似ID，然后调整顺序
                        if (ev.clientX - item.offset().left > 0.7 * item.width()) {
                            change_order(controls, source, target, 0, "item", "row");
                        }
                        else {
                            change_order(controls, source, target, 1, "item", "down");
                        }
                        data.endSelect = true;
                        amis.embed(
                            '#' + page_html_id + " .config-part", amisJSON, { data: { data } }, { theme: 'antd' }
                        );
                        ev.stopPropagation();
                    }
                }
                else {
                    let item = $(element);
                    element.ondragstart = function (ev) {
                        item.css("background", "#ddd");
                        ev.dataTransfer.setData("Text", $(ev.target).data("id")); //将类似ID的属性传递
                        ev.stopPropagation();
                    }
                    element.ondragover = function (ev) {
                        //根据鼠标位置判断放到组内还是组外
                        if (ev.clientX - item.offset().left > 0.7 * item.width()) {
                            item.parent().parent().css("border", null);
                            item.parent().parent().css("border-bottom", null);
                            item.css("border-right", "solid 5px #1890ff");
                        }
                        else if (ev.clientX - item.offset().left < 0.3 * item.width()) {
                            item.css("border-right", null);
                            item.parent().parent().css("border-bottom", null);
                            item.parent().parent().css("border", "solid 2px #1890ff");
                        }
                        else {
                            item.parent().parent().css("border", null);
                            item.css("border-right", null);
                            item.parent().parent().css("border-bottom", "solid 3px #1890ff");
                        }
                        ev.preventDefault();
                        ev.stopPropagation();
                    }
                    element.ondragleave = function (ev) {
                        item.parent().parent().css("border", "");
                        item.css("border-right", "");
                        item.parent().parent().css("border-bottom", "");
                        item.css("background", "");
                    }
                    element.ondrop = function (ev) {
                        item.css("border-right", "");
                        item.parent().parent().css("border", "");
                        item.parent().parent().css("border-bottom", "");
                        item.css("background", "");
                        //自动组号
                        auto_group_no(controls);
                        var source = ev.dataTransfer.getData("Text");
                        item.parent().parent().css("border-bottom", "");
                        let target = index;
                        //这里获取到类似ID，然后调整顺序
                        if (ev.clientX - item.offset().left > 0.7 * item.width()) {
                            change_order(controls, source, target, 0, "fieldSet", "row");
                        }
                        else if (ev.clientX - item.offset().left < 0.3 * item.width()) {
                            change_order(controls, source, target, 1, "fieldSet", "in"); //放到里面
                        }
                        else {
                            change_order(controls, source, target, 1, "fieldSet", "down");
                        }
                        data.endSelect = true;
                        amis.embed(
                            '#' + page_html_id + " .config-part", amisJSON, { data: { data } }, { theme: 'antd' }
                        );
                        ev.stopPropagation();
                    }
                }
            });
            let form = $(scope).find(".antd-Panel--form");
            form.each((index, element) => {
                let is_fieldset = element.localName == "fieldset";
                let item = $(element);
                element.ondragover = function (ev) {
                    item.css("border", "solid 2px #1890ff");
                    ev.preventDefault();
                }
                element.ondragleave = function (ev) {
                    item.css("border", "");
                }
                element.ondrop = function (ev) {
                    item.css("border", "");
                    //自动组号
                    auto_group_no(controls);
                    var source = ev.dataTransfer.getData("Text");
                    item.css("border-bottom", "");
                    let target = items.length - 1;
                    //这里获取到类似ID，然后调整顺序
                    change_order(controls, source, target, 1, "form", "in"); //放到里面
                    data.endSelect = true;
                    amis.embed(
                        '#' + page_html_id + " .config-part", amisJSON, { data: { data } }, { theme: 'antd' }
                    );
                    ev.stopPropagation();
                }
            });
            items.find(".item-close").off("click").on("click", function () {
                let index = $(this).data("id");
                let ci = 0
                for (let i in controls) {
                    let c = controls[i];
                    if (ci == index) {
                        controls.splice(i, 1);
                    }
                    ci++;
                    if (c.type == "fieldSet") {
                        for (let i in c.body) {
                            if (ci == index) {
                                c.body.splice(i, 1);
                            }
                            ci++;
                        }
                    }
                }
                data.endSelect = true;
                amis.embed(
                    '#' + page_html_id + " .config-part", amisJSON, { data: { data } }, { theme: 'antd' }
                );
            })
            let new_items = $('#' + page_html_id + " .new-item");
            new_items.each((index, element) => {
                element.ondragstart = function (ev) {
                    ev.dataTransfer.setData("Text", $(ev.target).data("type")); //将类似ID的属性传递
                }
            });
        }

        //定时同步刷新预览
        let interval = window.setInterval(refresh, 500);
    }
}

let auto_group_no = function (controls) {
    let max = 0;
    let pre_no;
    controls.forEach(function (item, index) {
        if(pre_no && pre_no==item.group_no){
            pre_no=item.group_no;
            item.group_no = max;
        }
        else{
            pre_no=item.group_no;
            item.group_no = max+1;
            max++;
        }
    })
    controls.filter(c => c.type == "fieldSet").forEach(function (fs, index) { //fieldSet内部的           
        let controls = fs.body;
        let max = 0;
        let pre_no;
        if(!controls){
            return;
        }
        controls.forEach(function (item, index) {
            if(pre_no && pre_no==item.group_no){
                pre_no=item.group_no;
                item.group_no = max;
            }
            else{
                pre_no=item.group_no;
                item.group_no = max+1;
                max++;
            }
        })
    })
}

let change_order = function (controls, source, target, group_no_bias, target_type, target_position) {
    let ci = 0;
    let source_parent;
    let source_index;
    let target_parent;
    let target_index;
    let target_group_no;
    for (let i in controls) {
        i=parseInt(i);
        let c = controls[i];
        if (!isNaN(source) && ci == source) {
            source_parent = controls;
            source_index = i;
        }
        if (ci == target || (group_no_bias > 0 && c.group_no == target_group_no)) {
            target_parent = controls;
            target_index = i;
            target_group_no = c.group_no;
            if (c.type == "fieldSet" && target_type=="fieldSet") {
                if (target_position == "in") { //插到内部
                    if(!c.body){
                        c.body=[];
                    }
                    target_parent = c.body;
                    target_index = c.body?(c.body.length - 1):0;
                    target_group_no = c.body && c.body.length > 0 ? c.body[c.body.length - 1].group_no : 0;
                }
            }
        }
        ci++;
        if (!target_parent && c.type == "fieldSet") {
            for (let j in c.body) {
                j=parseInt(j);
                if (!isNaN(source) && ci == source) {
                    source_parent = c.body;
                    source_index = j;
                }
                if (ci == target || (group_no_bias > 0 && c.body[j].group_no == target_group_no)) {
                    target_parent = c.body;
                    target_index = j;
                    target_group_no = c.body[j].group_no;
                }
                ci++;
            }
        }
    }
    if (!target_parent) {
        target_parent = controls;
        target_index = 0;
    }
    if (target_type=="form") {
        target_parent = controls;
        target_index = controls.length-1;
    }
    if (group_no_bias > 0) { //如果添加到下面，后面的需要重排组号，留出插入空间
        for (let i in target_parent) {
            if (i > target_index) {
                target_parent[i].group_no = target_parent[i].group_no + group_no_bias;
            }
        }
    }
    if (!isNaN(source)) { //属于拖动老控件
        let temp = source_parent[source_index];
        source_parent[source_index].group_no = target_group_no + group_no_bias; //group_no_bias=0加到尾部 group_no_bias=1加到下部
        source_parent.splice(source_index, 1); //删除源
        target_parent.splice((source_parent == target_parent && target_index > source_index) ? target_index : target_index + 1, 0, temp); //添加到目标后
    }
    else { //拖进新控件
        let temp = {
            "type": source,
            "name": "名称",
            "group_no": (target_group_no ? target_group_no : 0) + group_no_bias
        }
        if (target_parent) {
            target_parent.splice(target_index + 1, 0, temp); //添加到目标后
        }
    }

}

let build_form_controls = function (controls, parent_i) {
    if (!controls) return [];
    let add_form_controls = [];
    let add_form_controls_group = [];
    let pre_group_no;
    let pre_group;
    for (let i in controls) { //all fields
        let c = controls[i];
        let name = c.field_name;
        let label = c.name;
        let type = c.type;
        let add_form_control = {
            type: "text",
            name: name,
            label: label,
            className: "c_" + (parent_i ? parent_i + "_" : "") + i,
            required: c.required
        }
        if (type == "textarea") {
            add_form_control.type = "textarea";
        }
        else if (type == "number") {
            add_form_control.type = "input-number";
        }
        else if (type == "date") {
            add_form_control.type = "input-date";
        }
        else if (type == "datetime") {
            add_form_control.type = "input-datetime";
        }
        else if (type == "switch") {
            add_form_control.type = "switch";
        }
        else if (type == "file") {
            add_form_control.type = "input-file";
        }
        else if (type == "image") {
            add_form_control.type = "input-image";
        }
        else if (type == "password") {
            add_form_control.type = "input-password";
        }
        else if (type == "select") { //下拉选框
            add_form_control.type = "select";
        }
        else if (type == "radios") { //单选列表
            add_form_control.type = "radios";
            add_form_control.options = c.options;
        }
        else if (type == "checkboxes") { //多选列表
            add_form_control.type = "checkboxes";
            add_form_control.options = c.options;
        }
        else if (type == "related") { //关联表选择
            add_form_control.type = false ? "tree-select" : "picker";
        }
        else if (type == "fieldSet") { //分组容器
            add_form_control.type = "fieldSet";
            add_form_control.title = label;
            add_form_control.collapsable = true;
            add_form_control.body = build_form_controls(c.body, i);
        }
        //Form的分组处理
        let group_no = c.group_no;
        if (group_no) {
            if (group_no != pre_group_no) {
                let new_group_no = group_no + "_" + Math.random();
                add_form_controls_group[new_group_no] = [];
                pre_group = add_form_controls_group[new_group_no];
            }
            pre_group.push(add_form_control);
        }
        else {
            let group_no = "not_in_group_" + Math.random();
            add_form_controls_group[group_no] = [add_form_control];
            pre_group = add_form_controls_group[group_no];
        }
        pre_group_no = group_no;

    }
    //Form的分组处理
    for (let group_controls of Object.values(add_form_controls_group)) {
        let group = {
            "type": "group",
            "controls": group_controls
        };
        add_form_controls.push(group);
    }
    return add_form_controls;
}

export default page_type;